<?php
/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2020-11-26 18:10:22
 * @LastEditors: ding-cx
 * @LastEditTime: 2020-12-02 09:12:59
 * @Description: 用户相关功能。登录、登出、注册
 */
 
class ServiceUser extends Service
{
    public function __construct()
    {
        parent::__construct();
    }

    
    /* 登录 */
    public function login()
    {
        $data = $this->input->post();
        $this->load->entity('sys/EntityUser', 'entity_user');
        $this->load->entity('sys/EntityCaptcha', 'entity_cap');
        
        
        //    echo json_encode( $this -> entity_user ->valid(['userName','password']));
        $valid_user = $this -> entity_user ->valid(['user_name','password']);
        $valid_cap = $this -> entity_cap ->valid(['cap_uuid']);
        
        $result = $this->merge_valid(array($valid_user,$valid_cap));
        /* 如果表单验证未通过 */
        if (!$result['result']) {
            $this->send($result,50100);
            return ;
        }

        $this->db->where(array('cap_uuid' => $data['cap_uuid']));
        $dbword = $this->db->get('sys_captcha')->result_array();
        if(!empty($dbword)){
            $dbword = $dbword[0];
        }else{
<<<<<<< HEAD
           return $this->send("验证码无，刷新重试。",50000);
=======
           return $this->send("uuid没有对应二维码，刷新重试。",50000);
>>>>>>> 00985b19206a2c585f1c328e92bbe227e5fee301
        }

        /* 验证数据库的word跟用户输入的是否一致 */
        if(strtolower($dbword['word']) === strtolower($data['word'])){
            // $this->send("验证码通过，继续验证用户密码");
        }else{
           return $this->send("验证码错误",50000);
        }

        $this->db->where(array('user_name' => $data['user_name']));
        $this->db->where(array('password' => $data['password']));
        $dbUser = $this->db->get('sys_user')->result_array();
        if(!empty($dbUser)){
            $dbUser = $dbUser[0];
            
            $token = $this->createJwtToken($dbUser);
            
            if(config_item("is_install_redis")){
                // 登录通过 将用户信息存入redis。记住用户登录状态。
                $this->load->driver('cache');
                $this->cache->redis->save($dbUser['user_name'],$token,config_item('login_exp'));
            }
            
            return $this->send(array('token' =>$token,'msg'=>"登录成功"));
        }else{
            return $this->send("用户名或密码错误",50000);
        }
    }


    /**
     * @description: 创建jwttoken
     * @param {array} userData 要作为载荷的用户信息
     * @return {string} token 返回token
     */
    private function createJwtToken($userData){
        $this->load->library('Jwt');
        $jwt=new Jwt();
         
        $payload=array(
            'iss'=>'dingadmin',
            'iat'=>time(),
            'exp'=>time()+config_item('login_exp'),
            'nbf'=>time(),
            'sub'=>$userData['user_id'],
            'name' => $userData['user_name'],
            'jti'=>md5(uniqid('JWT').time()),
            'uid'=>$userData['user_id'],
        );

        $token=$jwt->getToken($payload);
        return $token;
    }

    /* 根据uid获取用户详细信息，此处需查询数据库 */
    public function getInfos($uid){
        $ret = array(
            // "roles" => array('editor'),
            "roles" => array('admin'),
            "introduction" => 'I\'m am editor.',
            "avatar" => "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
            "name" => "normal editor"
        );
        $this->send($ret);
    }
}
